<?php

/**
 * 
 * @author NutMotion <simonotm.linux@gmail.com> 
 */
require_once(dirname(__FILE__) . "/bookmarksRead.php");
require_once(dirname(__FILE__) . "/bookmarksCreate.php");
require_once(dirname(__FILE__) . "/bookmarksDelete.php");
require_once(dirname(__FILE__) . "/../commons/common-funcs.php");
require_once(dirname(__FILE__) . "/../db/common-operations.php");
require_once(dirname(__FILE__) . "/../db/associations.php");
require_once(dirname(__FILE__) . "/../db/bookmarksOperations.php");
require_once(dirname(__FILE__) . "/../db/tagsOperations.php");

//we control the presence of the required parameters 
//we'll leave (critical) further controls on the values to a future version

if (!isset($_POST['action']) && !isset($_GET['action'])) {
//    $what=buildHtmlPresentationForError(__FILE__, __FUNCTION__, buildJSONErrorString($_POST)." Required parameter 'action' is missing. Can't process the request...");
    echo buildHtmlPresentationForError(__FILE__, __FUNCTION__, " Required parameter 'action' is missing. Can't process the request...");
    exit();
}

if (isset($_POST['action'])) {
    $action = $_POST['action'];

    if (strcasecmp($action, "read") == 0) {
        echo handleReadOperation($_POST);
    } else if (strcasecmp($action, "searchBySingleTag") == 0) {
        handleSearchBySingleTag($_POST);
    } else if (strcasecmp($action, "create") == 0) {
        handleCreateOperation($_POST);
    } else if (strcasecmp($action, "delete") == 0) {        
        echo json_encode(handleDeleteByUrlAndTag($_POST));       
    } else {
        echo buildHtmlPresentationForError(__FILE__, __FUNCTION__, " Invalid value '$action' for parameter 'action'...");
    }
} else {
    $action = $_GET['action'];
    if (strcasecmp($action, "read") == 0) {
        echo handleReadOperation($_GET);
    }
}

// returns either the JSON result if the operation was successful, or an error msg with details about the cause of failure
function handleReadOperation($request) {

    if (isSet($request['tags-id'])) {

        //we split the tags-id param that comes from ajax (separator is space)
//        $partsTagsId=split(" ",$request['tags-id']); //PHP split function is deprecated.
        $partsTagsId = explode(" ", $request['tags-id']);

        connect();
//        $allResults = dbGetBookmarksIdsOfTagsIds($request['tags-id']);
        $allResults = array();
        $allResults['bookmarks'] = dbGetBookmarksOfTagsIds($partsTagsId);

        echo json_encode($allResults);
    } else if (isSet($request['req'])) {
//format : req=ta,u,ti&res=ta,u,ti
        echo json_encode(handleSearchTmp($request));
    } else if (isSet($request['term'])) {
        echo json_encode(handleSearchForJquery($request));
    }
    else if (isSet($request['fields'])) {
        echo json_encode(handleSearch($request));
    } else {
        echo buildHtmlPresentationForError(__FILE__, __FUNCTION__, "Parameter tags-id is required. Only parameter available for action 'read' for the moment...");
    }
}



/*
 * This function dedicated to handling the Bookmarks-searchBySingleTag operation. 
 * It expects the $_POST parameter, and outputs the results directly to the Http stream.
 * Output format is the JSON representation the ResultContext object we build in the function.
 * 
 * ~~ IN

  Example query received:

  {"action":"searchBySingleTag",
  "keyword":"job-IT-career"}
 * ~~ OUT

  Example query response:

  {"success":"true",
  "arFeedbackMsgs":[{"default":"Correctly retrieved 1 webpage"}],
  "arReturnedValues":[
 *      {"default":[
 *          "0":[
 *              "url":"http:\/\/www.linux.com\/learn\/careers-training\/363-the-linux-career-guide",
  "title":"The Linux Career Guide | Linux.com"}]}
 *          ],
 * *        "1":[
 *              "url":"http:\/\/www.linux.com\/learn\/careers-training\/363-the-linux-career-guide",
  "title":"The Linux Career Guide | Linux.com"}]}
 *          ]
 *      ]}
 * ]}
 * 
 * @param request This is just a copy ("reference"?) of the $_POST array
 */

function handleSearchBySingleTag($request) {
    /* Variable for tracking the state and data of the operation
     * ---------------------------------------------------------
     * Fields which are bound to be injected in the final ResultContext object are encapsulated inside a dedicated local variable.
     */

//The state
    $success = false; //tracks the success or failure of the operation.
//The data
    $arFeedbackMsg = array(); //stores feedback message(s) about the "unfolding" of this operation.
    $arReturnResults = array(); //stores the entities fetched from the Model layer.

    /* Additional variables for storing data
     * ---------------------------------------------------------
     */
    $keywordFromQuery = $_POST['keyword']; // the "keyword" parameter from the Bookmarks-searchBySingleTag POST query.
//$arMatchingTags
//---------------
//associative array which stores each tags which match the keyword.
//Format:
//$arMatchingTags["$tagId"]=array("id"=>"$tagId", "tag"=>$tag)
    $arMatchingTags = array();

//$arMatchingBookmarks
//--------------------
//array which stores infos about the web pages and tags we've found based on the keyword.
//Format:
//$arMatchingBookmarks[]=array("url","title","tag1","tag2", ... "tagN")
    $arMatchingBookmarks = array();


    /* Misc variable for support
     * ---------------------------------------------------------
     */
    $arDbQueryResult;
    $nbTagsMatching = 0;
    $nbWebpagesFound = 0;
    /* There we go
     * ---------------------------------------------------------
     */

    connect(); //needed...


    /* Interactions with the Model layer
     * ---------------------------------------------------------
     */

    // 1) we check whether there's one (or more) tags which "tag" field matches the keyword.
    //SELECT id FROM webpage WHERE url='h'
    $arDbQueryResult = selectFromTable("tags", "id,tag", "tag LIKE '%" . $keywordFromQuery . "%'");
    $countResultNb = count($arDbQueryResult);
    //Assumption: I'm not even sure about the format of the db rows returned by selectFromTable
    //assuming I'll get something like array(0=>array("id"=>"1"),1=>array("id"=>"2")) in case there's 2 results, for example.
    if ($countResultNb >= 0) {
        //we've found one or more tags which match the keyword : we add them to our $arMatchingTags temp array
        for ($i = 0; $i < $countResultNb; $i++) {

            $tagId = $arDbQueryResult[$i]["id"];
//            //we add it only IF it doesn't exist yet
//            if (!isSet($arMatchingTags["$tagId"])) {
            $arMatchingTags["$tagId"] = array("id" => "$tagId", "tag" => $arDbQueryResult[$i]["tag"]);
            $nbTagsMatching++;
//            }
        }
    }

    // 2) for each of the tags found in 1) (if any), we search for webpages associated with them.
    foreach ($arMatchingTags as $tagId => $dummyValue) {

        //SELECT webpage_id FROM webpage_has_tags WHERE tags_id=24
        $arDbQueryResult = selectFromTable("webpage_has_tags", "webpage_id", "tags_id=$tagId");
        $countResultNb = count($arDbQueryResult);

        if ($countResultNb >= 0) {
            //we've found one or more webpages associated with this tag : we add them to our $arMatchingTags temp array
            for ($i = 0; $i < $countResultNb; $i++) {

                $webpageId = $arDbQueryResult[$i]["webpage_id"];


                if (!isSet($arMatchingBookmarks["$webpageId"])) {
                    //first time we encounter this webpageId : we create a new entry
                    $arMatchingBookmarks["$webpageId"] = array();
                }

                //we also store the tag for later use
                $arMatchingBookmarks["$webpageId"][] = $arMatchingTags["$tagId"]["tag"];
            }
        }
    }

    // 3) Finally, we retrieve all web pages found!  
    $arReturnResults["default"] = array();

    foreach ($arMatchingBookmarks as $webpageId => $dummyValue) {

        $arDbQueryResult = selectFromTable("webpage", "url, title", "id=$webpageId");

        if (count($arDbQueryResult) > 0) {
            //there should be only one webpage for this webpage_id !
            $nbWebpagesFound++;

            $success = true;

            $arReturnResults["default"][] = array("url" => $arDbQueryResult[0]["url"], "title" => $arDbQueryResult[0]["title"], "tag" => $arMatchingBookmarks["$webpageId"]);
        }
    }


    if ($success) {
        $arFeedbackMsg["default"] = "Found $nbWebpagesFound bookmarks";
    } else if (!isset($arFeedbackMsg["default"])) {
        $arFeedbackMsg["default"] = "The server has encountered a problem. Nb tags matching for tag '$keywordFromQuery': $nbTagsMatching. Nb web pages: $nbWebpagesFound";
    }

    echo json_encode(new ResultContext($success, $arReturnResults, $arFeedbackMsg));
}


//this is just a "proxy" to format the tags data from function handleSearch to the format
//needed by jquery autocomplete plugin
function handleSearchForJquery($request) {
    $arFinalTags = array();

    $request["key"] = $request["term"];
    $resultContext = handleSearchTmp($request);

    if (isset($resultContext->arReturnParameter["default"])) {
        $arTags = $resultContext->arReturnParameter["default"];



        //we must replace the key from "tag" to "value"
        //ie array("tag"=>tag, ...)
        //by array ("value"=>tag, ...)
        foreach ($arTags as $tag => $tagValue) {
            $arFinalTags[] = array("value" => $tagValue["tag"]);
        }
    }

    return $arFinalTags;
}
?>

